package mylab.io.store.socket.tcp.server;

import com.google.common.base.Preconditions;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import mylab.io.base.model.Msg;
import mylab.io.base.util.DasUtil;
import mylab.io.core.AbstractServerDas;
import mylab.io.core.context.DefaultCC;
import mylab.io.store.socket.property.TcpServerProperties;

public class TcpServerDas<M extends Msg>
        extends AbstractServerDas<TcpServerProperties, M, TcpServerCodec<M>, ByteBuf> {

    public TcpServerDas(DefaultCC<TcpServerProperties, M> context, TcpServerCodec<M> codec) {
        super(context, codec);
    }

    @Override
    protected ChannelFuture actualStart() throws Exception {
        Preconditions.checkState(DasUtil.isValidEndpoint(properties.getListen()), "invalid endpoint");

        masterGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
        childGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());

        bootstrap = new ServerBootstrap();
        bootstrap.group(masterGroup, childGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(codec.getChannelInitializer());

        return bootstrap.bind(properties.getListen().getAddress());
    }

}
